import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
import router from '@/router'

// 1 创建axios实例
// create an axios instance
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 2.配置请求拦截器
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // 2.1 判断是否有token
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 3 响应拦截器
// response interceptor
service.interceptors.response.use(
  (response) => {
    // axios默认包裹了data
  // 判断是不是Blob
    if (response.data instanceof Blob) return response.data // 返回了Blob对象
    // 3.1解析数据
    const { data, msg, code } = response.data
    // 3.2判断：请求成功切业务成功 / 请求成功但业务失败
    if (code === 10000) {
      return data
    } else {
      return Promise.reject(new Error(msg))
    }
  },
  async error => {
    // 3.3 token失效处理
    if (error.response.status === 401) {
      Message.error('登录过期了~~~')
      // 1.退出登录页清空用户信息
      await store.dispatch('user/logout')
      // 2.跳转到登录
      router.replace('/login')
    } else {
      // 错误统一处理
      Message({
        message: error.response.data.msg,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
